import axios, { type AxiosError, type AxiosRequestConfig } from 'axios'

import type { Res } from '@/types/http'

const instance = axios.create({
  baseURL: 'https://consult-api.itheima.net'
})

import { useUserStore } from '@/stores/index'

// 请求拦截器  在请求发起前进行配置修改
instance.interceptors.request.use(
  (config) => {
    const useStore = useUserStore()
    const token = useStore.token
    console.log()
    let userConfigHeaders = {}
    // authorization Btoken
    if (token) {
      userConfigHeaders = { authorization: 'Btoken ' + token }
    }
    config.headers = Object.assign({}, userConfigHeaders, config.headers)

    // config代表axios的配置
    return config
  },
  (err) => {
    // 配置出现错误，接受错误
  }
)

// 响应拦截器
instance.interceptors.response.use(
  (res) => {
    // 请求成功的数据
    if (res.data.code === 10000) {
      return res.data
    } else {
      return Promise.reject({
        response: {
          message: res.data.message
        }
      })
    }
  },
  (err: AxiosError) => {
    // 请求失败的结果或者上面处理失败的结果
    return err.response
  }
)

const http = <T>(config: AxiosRequestConfig) => {
  return instance<T, Res<T>>(config)
}

http.get = <T>(url: string, config?: AxiosRequestConfig) => {
  return instance.get<T, Res<T>>(url, config)
}

http.post = <T, Data>(url: string, data?: Data, config?: AxiosRequestConfig) => {
  return instance.post<T, Res<T>>(url, data, config)
}

http.put = <T, Data>(url: string, data?: Data, config?: AxiosRequestConfig) => {
  return instance.put<T, Res<T>>(url, data, config)
}

http.delete = <T>(url: string, config?: AxiosRequestConfig) => {
  return instance.delete<T, Res<T>>(url, config)
}

export default http as typeof http
